package com.example.settings.controller;

import com.example.settings.domain.User;
import com.example.settings.service.UserService;
import com.example.settings.service.impl.UserServiceimpl;
import com.example.utils.MD5Util;
import com.example.utils.PrintJson;
import com.example.utils.ServiceFactory;
import com.example.utils.SqlSessionUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("进入到用户控制器");
        String path = request.getServletPath();
        if ("/settings/user/login.do".equals(path)){
            login(request,response);
        }
    }



    private void login(HttpServletRequest request, HttpServletResponse response){

        System.out.println("进行登录验证");
        String loginAct = request.getParameter("loginAct");
        String loginPwd = request.getParameter("loginPwd");
        String ip = request.getRemoteAddr();
        loginPwd = MD5Util.getMD5(loginPwd);

        UserService userService = (UserService) ServiceFactory.getService(new UserServiceimpl());

        try{
            User user = userService.login(loginAct,loginPwd,ip);

            request.getSession().setAttribute("user",user);

            PrintJson.printJsonFlag(response,true);
        }catch (Exception e){
            e.printStackTrace();

            String msg  = e.getMessage();
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("success",false);
            map.put("msg",msg);
            PrintJson.printJsonObj(response,map);
        }
    }
}
